package com.heba.greenmulu.user;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.heba.ATApp;
import com.heba.Cfg;
import com.heba.Debug;
import com.heba.bean.ItemAreaObject;
import com.heba.bean.user.UserObject;
import com.heba.config.CommonConfig;
import com.heba.dialog.CustomDialogView;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.businesslist.BusinessEditActivity;
import com.heba.helper.FileUploadHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.helper.TakePhotoHelper;
import com.heba.helper.UploadPhotoHelper;
import com.heba.helper.callback.FileUploadListener;
import com.heba.permission.PermissionHelper;
import com.heba.popupwindow.AddressPopupWindow;
import com.heba.popupwindow.PhotoPopupWindow;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.utils.ImageTools;
import com.heba.utils.ToastShow;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 編輯用戶資料
 * Created by jason on 2020/1/3.
 */
public class UserEditActivity extends BaseActivity {

    private View view_background;
    private EditText et_account, et_nickName, et_desc, et_website, et_email, et_wechat, et_facebook, et_mobile;
    private ImageView iv_avatar;
    private Button btn_female, btn_male;
    private TextView tv_address;

    private ImageView iv_bannar;
    private int clickBannar = 0;
    /**
     * 头像上传
     */
    private PhotoPopupWindow photoPopupWindow;
    private File tempFile;   //头像保存路径
    private File bannarFile;
    private int crop = 500;  //裁剪大小

    /**
     * 地址弹出框
     */
    private AddressPopupWindow addressPopupWindow;
    private List<ItemAreaObject> itemAreaObjects = new ArrayList<>();

    private UserObject userObject;

    /**
     * 上传的资料信息
     */
    private String bannarUrl = "";
    private String pictureUrl = "";   //上传图片地址
    private int sex;
    private String address;
    private String addressEn;

    private CallbackManager callbackManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_edit);
        callbackManager = CallbackManager.Factory.create();
        initTopbar();
        findViewById();
        setContentTextView();
        initView();
        initPopWindow();
        facebookLoginManager();
    }

    @Override
    protected void findViewById() {
        view_background = findViewById(R.id.view_background);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.mine_edit_account));
        txt_right.setText(getResources().getString(R.string.mine_edit_finish));

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            userObject = (UserObject) bundle.getSerializable(CommonConfig.USER_OBJECT);
        }

        //设置account只允许输入字母和数字
        et_account.setKeyListener(DigitsKeyListener.getInstance("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
        iv_bannar.setOnClickListener(v -> {
            clickBannar = 0;
            view_background.setVisibility(View.VISIBLE);
            getCameraPermission();
        });
        iv_avatar.setOnClickListener(v -> {
            clickBannar = 1;
            view_background.setVisibility(View.VISIBLE);
            getCameraPermission();
        });

        btn_female.setOnClickListener(v -> {
            btn_male.setSelected(false);
            btn_female.setSelected(true);
            sex = 2;
        });

        btn_male.setOnClickListener(v -> {
            btn_male.setSelected(true);
            btn_female.setSelected(false);
            sex = 1;
        });

        /**
         * 綁定微信处理
         */
        et_wechat.setOnClickListener(v -> {
            if (userObject.getIsBindWechat() == 1)
                return;
            bindWechat();
        });

        /**
         * 绑定facebook处理
         */
        et_facebook.setOnClickListener(v -> {
            if (userObject.getIsBindFaceBook() == 1)
                return;
            bindFacebook();
        });

        /**
         * 地址选择
         */
        tv_address.setOnClickListener(v -> {
            addressPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
            view_background.setVisibility(View.VISIBLE);
        });

        /**
         * 提交编辑用户信息
         */
        txt_right.setOnClickListener(v -> {
            commitUserEditInfo();
        });

        setUserInfoView(userObject);
    }

    /**
     * 初始化PopupWindow
     */
    private void initPopWindow() {
        /**
         * 照片弹出框
         */
        photoPopupWindow = new PhotoPopupWindow(this, ViewGroup.LayoutParams.MATCH_PARENT, DensityUtils.dip2px(this, 165));

        photoPopupWindow.setOnPhotoPopupClickListener(new PhotoPopupWindow.OnPhotoPopupClickListener() {
            @Override
            public void onCameraClick() {
                if (clickBannar == 0){
                    bannarFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getFileName());
                    TakePhotoHelper.takePicture(UserEditActivity.this, bannarFile);
                }else{
                    tempFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getFileName());
                    TakePhotoHelper.takePicture(UserEditActivity.this, tempFile);
                }
            }

            @Override
            public void onAlbumClick() {
                if (clickBannar == 0){
                    bannarFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getFileName());
                    TakePhotoHelper.selectPhoto(UserEditActivity.this);
                }else{
                    tempFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getFileName());
                    TakePhotoHelper.selectPhoto(UserEditActivity.this);
                }
            }

            @Override
            public void onCancelClick() {

            }
        });

        photoPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });

        /**
         * 地址弹出框
         */
        addressPopupWindow = new AddressPopupWindow(this, DensityUtils.getWidth(this),
                2 * DensityUtils.getHeight(this) / 5);
        addressPopupWindow.adapter = new AddressPopupWindow.ItemListAdapter(this, itemAreaObjects);
        addressPopupWindow.listView.setAdapter(addressPopupWindow.adapter);

        addressPopupWindow.setOnCategoryPopupClickListener(new AddressPopupWindow.OnAddressPopupClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ItemAreaObject object = (ItemAreaObject) parent.getItemAtPosition(position);
                address = object.getLocationZH();
                addressEn = object.getLocationEN();
                if (Cfg.Leng == 0) {
                    tv_address.setText(object.getLocationEN());
                } else {
                    tv_address.setText(object.getLocationZH());
                }
            }
        });

        addressPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 設置text文字
     */
    private void setContentTextView() {
        int[] viewIDs = new int[]{R.id.view_banner,R.id.view_photo, R.id.view_account, R.id.view_name, R.id.view_desc,
                R.id.view_website, R.id.view_email, R.id.view_wechat, R.id.view_facebook, R.id.view_tel, R.id.view_gender, R.id.view_area};
        String[] strTexts = getResources().getStringArray(R.array.mine_edit_datas);
        for (int i = 0; i < viewIDs.length; i++) {
            findContentTextView(viewIDs[i], strTexts[i]);
        }
    }

    /**
     * findContentTextView
     *
     * @param viewID
     * @param text
     */
    private void findContentTextView(int viewID, String text) {
        View view = findViewById(viewID);
        TextView textView = view.findViewById(R.id.textview);
        textView.setText(text);

        switch (viewID) {
            case R.id.view_banner:
                iv_bannar = view.findViewById(R.id.iv_bannar);
                break;
            case R.id.view_photo:
                iv_avatar = view.findViewById(R.id.iv_avatar);
                break;
            case R.id.view_account:
                et_account = view.findViewById(R.id.et_text);
                break;
            case R.id.view_name:
                et_nickName = view.findViewById(R.id.et_text);
                break;
            case R.id.view_desc:
                et_desc = view.findViewById(R.id.et_desc);
                break;
            case R.id.view_website:
                et_website = view.findViewById(R.id.et_text);
                break;
            case R.id.view_email:
                et_email = view.findViewById(R.id.et_text);
                et_email.setFocusable(false);
                et_email.setFocusableInTouchMode(false);
                et_email.setEnabled(false);
                break;
            case R.id.view_wechat:
                et_wechat = view.findViewById(R.id.et_text);
                break;
            case R.id.view_facebook:
                et_facebook = view.findViewById(R.id.et_text);
                break;
            case R.id.view_tel:
                et_mobile = view.findViewById(R.id.et_text);
                break;
            case R.id.view_gender:
                btn_male = view.findViewById(R.id.btn_male);
                btn_female = view.findViewById(R.id.btn_female);
                break;
            case R.id.view_area:
                tv_address = view.findViewById(R.id.txt_address);
                break;
            default:
                break;
        }
    }

    /**
     * 显示用户信息
     */
    private void setUserInfoView(UserObject object) {
        pictureUrl = object.getIcon();
        bannarUrl = object.getBannerUrl();
        sex = object.getSex();
        address = object.getAddress();
        addressEn = object.getAddressen();

        et_wechat.setFocusable(false);
        et_wechat.setFocusableInTouchMode(false);
        et_facebook.setFocusable(false);
        et_facebook.setFocusableInTouchMode(false);

        et_mobile.setInputType(InputType.TYPE_CLASS_NUMBER);
        GlideUtil.loadImageWithPlaceHolderID(this, object.getIcon(), iv_avatar, R.drawable.icon_head_portrait);
        GlideUtil.loadImageWithDefaultPlaceHolder(this, object.getBannerUrl(), iv_bannar);
        et_account.setText(object.getAccount());
        et_nickName.setText(object.getNickname());
        et_desc.setText(CommonUtils.getDecodeText(object.getProfile()));
        et_website.setText(object.getWebside());
        et_mobile.setText(object.getMobile());
        et_email.setText(object.getEmail());
        /**
         * 微信绑定
         */
        if (object.getIsBindWechat() == 1) {
            et_wechat.setText(getResources().getString(R.string.linked));
        } else {
            et_wechat.setText(getResources().getString(R.string.not_linked));
        }
        /**
         * facebook绑定
         */
        if (object.getIsBindFaceBook() == 1) {
            et_facebook.setText(getResources().getString(R.string.linked));
        } else {
            et_facebook.setText(getResources().getString(R.string.not_linked));
        }
        /**
         * 判断性别
         */
        if (object.getSex() == 1) {
            btn_male.setSelected(true);
        } else if (object.getSex() == 2) {
            btn_female.setSelected(true);
        }
        /**
         * 判断地址
         */
        tv_address.setText(Cfg.Leng == 1 ? object.getAddress() : object.getAddressen());

        /**
         * 地区数据
         */
        String[] location_zh = this.getResources().getStringArray(R.array.select_location_zh);
        String[] location_en = this.getResources().getStringArray(R.array.select_location_en);
        for (int i = 0; i < location_zh.length; i++) {
            ItemAreaObject itemAreaObject = new ItemAreaObject();
            itemAreaObject.setLocationZH(location_zh[i]);
            itemAreaObject.setLocationEN(location_en[i]);
            itemAreaObjects.add(itemAreaObject);
        }
    }

    /**
     * 提交编辑用户信息
     */
    private void commitUserEditInfo() {
        if (et_nickName.getText().toString().isEmpty()) {
            ToastShow.displayToast(this, getResources().getString(R.string.mine_edit_input_nickname));
            return;
        }

        if (et_account.getText().toString().length() < 6) {
            ToastShow.displayToast(this, getResources().getString(R.string.sign_up_account_input_tips));
            return;
        }

        progressDialog.show();
        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
            @Override
            public void Success() {
                progressDialog.dismiss();
                if (!Cfg.Icon.equals(pictureUrl)) {
                    //用户更改了头像,通知刷新头像
                    MessageEvent event = new MessageEvent();
                    event.setUserIcon(pictureUrl);
                    event.setBannarIcon(bannarUrl);
                    event.setEvent(CommonConfig.EVENT_UPDATE_ICON);
                    EventBus.getDefault().post(event);
                }
                ToastShow.displayToast(UserEditActivity.this, getResources().getString(R.string.update_success));
                finishActivity();
            }

            @Override
            public void Fail(String error) {
                progressDialog.dismiss();
            }
        }).setUserInfoV1(this, pictureUrl, et_account.getText().toString(), et_nickName.getText().toString(), CommonUtils.getEncodeText(et_desc.getText().toString()), et_website.getText().toString(),
                et_email.getText().toString(), et_mobile.getText().toString(), sex, address, addressEn,bannarUrl);
    }

    /**
     * --------------------------- 相册或拍照获取图片部分 ----------------------------------
     */

    /**
     * 获取摄像头,读取文件权限
     */
    private void getCameraPermission() {
        new PermissionHelper(UserEditActivity.this, new PermissionHelper.PermissionListener() {
            @Override
            public void onPermissionSuccess() {
                if (clickBannar == 0){
                    photoPopupWindow.showAtLocation(iv_bannar, Gravity.BOTTOM, 0, 0);
                }else{
                    photoPopupWindow.showAtLocation(iv_avatar, Gravity.BOTTOM, 0, 0);
                }
            }

            @Override
            public void onPermissionFailure() {

            }
        }).requestPermission(Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA);
    }


    /**
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TakePhotoHelper.TAKE_PICTURE:
                    // 拍照裁剪图片
                    if (clickBannar == 0){
                        TakePhotoHelper.cropImage16and9(UserEditActivity.this, bannarFile, Uri.fromFile(bannarFile), crop,
                                TakePhotoHelper.PICTURE_SEND);
                    }else {
                        TakePhotoHelper.cropImage(UserEditActivity.this, tempFile, Uri.fromFile(tempFile), crop,
                                TakePhotoHelper.PICTURE_SEND);
                    }
                    break;

                case TakePhotoHelper.CHOOSE_PICTURE:
                    // 相册选取图片去裁剪
                    if (data != null) {
                        if (clickBannar == 0){
                            TakePhotoHelper.cropImage16and9(UserEditActivity.this, bannarFile, data.getData(), crop,
                                    TakePhotoHelper.PICTURE_SEND);
                        }else{
                            TakePhotoHelper.cropImage(UserEditActivity.this, tempFile, data.getData(), crop,
                                    TakePhotoHelper.PICTURE_SEND);
                        }
                    }
                    break;

                case TakePhotoHelper.PICTURE_SEND:

                    if (clickBannar == 0){
                        if (bannarFile != null)
                            sentPicToNext(bannarFile);
                    }else {
                        if (tempFile != null)
                            sentPicToNext(tempFile);

                    }
                    break;

                default:
                    break;
            }
        }
    }

    /**
     * 将进行剪裁后的图片传递到下一个界面上
     *
     * @param file
     */
    private void sentPicToNext(File file) {
        //解决小米系统 retuen data 为null的问题
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.fromFile(file)));
            //图片路径
            String localPath = ImageTools.savePhotoToSDCard(this, bitmap, ImageTools.getUploadPathFolder(), ImageTools.getFileName(), false);
            String cosPath = "greenmulu/image/transfer_" + ImageTools.getFileName();
            if (bitmap != null) {
                /**
                 * 上传图片处理
                 */
                loading.Start();
                if (clickBannar == 0){
                    new MemberShipHelper(new MemberShipHelper.MembershipListener() {

                        @Override
                        public void Success() {
                            loading.End();
                        }

                        @Override
                        public void SamSuccess(String imageUrl) {
                            loading.End();
                            bannarUrl = imageUrl;
                            GlideUtil.loadImageWithPlaceHolderID(UserEditActivity.this, bannarUrl, iv_bannar, R.drawable.icon_scan_add_pic);
                        }

                        @Override
                        public void Fail(String error) {
                            loading.End();

                        }
                    }).uploadSamImage(this, file.getPath());
                }else{
                    UploadPhotoHelper photoHelper = new UploadPhotoHelper(this);;
                    photoHelper.compressSamPhoto(file, new FileUploadListener() {
                        @Override
                        public void onSuccess(String imgUrl) {
                            loading.End();
                            if (clickBannar == 0){
                                bannarUrl = imgUrl;
                                GlideUtil.loadImageWithPlaceHolderID(UserEditActivity.this, bannarUrl, iv_bannar, R.drawable.icon_scan_add_pic);
                            }else{
                                pictureUrl = imgUrl;
                                GlideUtil.loadImageWithPlaceHolderID(UserEditActivity.this, pictureUrl, iv_avatar, R.drawable.icon_head_portrait);
                            }
                        }

                        @Override
                        public void onFail() {
                            loading.End();

                        }
                    });
                }

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 绑定微信
     */
    private void bindWechat() {
        new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
            @Override
            public void onYesClick() {
                /**
                 * 调起微信授权
                 */
                if (!ATApp.api.isWXAppInstalled()) {
                    //引导用户去安装微信
                    ToastShow.displayToast(UserEditActivity.this, getResources().getString(R.string.wechat_install));
                    Uri uri = Uri.parse("market://details?id=com.tencent.mm");//id为包名
                    Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(it);
                    return;
                }
                //调起微信授权
                final SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "greenmulu_wx_bind";
                ATApp.api.sendReq(req);
            }

            @Override
            public void onNoClick() {

            }
        }).showDialog(UserEditActivity.this, UserEditActivity.this.getResources().getString(R.string.confirm_bind_wechat), "");
    }

    /**
     * 绑定facebook
     */
    private void bindFacebook() {
        new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
            @Override
            public void onYesClick() {
                LoginManager.getInstance().logInWithReadPermissions(UserEditActivity.this, Arrays.asList("public_profile"));
            }

            @Override
            public void onNoClick() {

            }
        }).showDialog(UserEditActivity.this, UserEditActivity.this.getResources().getString(R.string.confirm_bind_facebook), "");
    }

    /**
     * facebook回调
     */
    private void facebookLoginManager() {
        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        Debug.Log("facebook success", "loginResult");

                        /**
                         * 获取用户信息
                         */
                        AccessToken token = loginResult.getAccessToken();
                        GraphRequest request = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Debug.Log("Facebook UserInfo:", response.toString());
                                try {
                                    String id = object.getString("id");

                                    /**
                                     * 发送用户信息至服务器
                                     */
                                    progressDialog.show();
                                    new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                                        @Override
                                        public void Success() {
                                            userObject.setIsBindFaceBook(1);
                                            setUserInfoView(userObject);
                                            ToastShow.displayToast(UserEditActivity.this, getResources().getString(R.string.bind_success));
                                            progressDialog.dismiss();
                                        }

                                        @Override
                                        public void Fail(String error) {
                                            userObject.setIsBindFaceBook(0);
                                            ToastShow.displayToast(UserEditActivity.this, getResources().getString(R.string.bind_failure));
                                            progressDialog.dismiss();
                                        }
                                    }).bindFacebook(UserEditActivity.this, id);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        Bundle parameters = new Bundle();
                        parameters.putString("fields", "id,name,picture");
                        request.setParameters(parameters);
                        request.executeAsync();
                    }

                    @Override
                    public void onCancel() {
                        Debug.Log("facebook cancel", "facebook cancel by user");
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        Debug.Log("facebook error", "exception = " + exception.getMessage());
                        if (exception instanceof FacebookAuthorizationException) {
                            if (AccessToken.getCurrentAccessToken() != null) {
                                LoginManager.getInstance().logOut();
                            }
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Debug.Log("清理上传图片的文件夹", ImageTools.getUploadPathFolder().toString());
        //清理文件图片
        ImageTools.deleteAllPhoto(ImageTools.getUploadPathFolder());
    }
}
